/**
 顺序表：用一组地址连续的存储单元依次存储线性表的数据元素
 使用迭代器访问列表而不是数组索引，删除或者插入元素需要更新索引，而使用迭代器方式不需要。
 */



class ArrayList {
    constructor(){
        this.datas = []
        this.length = 0
        this.pos = 0
    }

    /**
     * 私有方法,搜索目标元素在列表的索引
     */
    _find(target){
        for(let i = 0; i < this.datas.length; i++){
            if(this.datas[i] === target){
                return i
            }
        }
        return -1
    }

    push(element){
        this.datas[this.length] = element
        this.length++
    }

    insert(element,afterEle){
        let inserIndex = this._find(afterEle)
        if(inserIndex > -1){
            this.datas.splice(inserIndex+1,0,element)
            this.length++
        }
    }

    toString(){
        return '['+this.datas.toString()+']'
    }

    remove(element){
        let eleIndex = this._find(element)
        if(eleIndex > -1){
            this.datas.splice(eleIndex,1)
            this.length--
        }
    }

    clear(){
        delete this.datas
        this.datas = []
        this.length = this.pos =0
    }

    curPos(){
        return this.pos
    }

    next(){
        if(this.pos <= this.length-1){
            this.pos++
        }
    }

    pre(){
        if(this.pos > 0){
            this.pos--
        }
    }

    front(){
        this.pos = 0
    }

    end(){
        this.pos = this.length - 1
    }

    moveTo(pos){
        this.pos = pos
    }

}

const arrayList = new ArrayList()

arrayList.push('A')
arrayList.push('B')
arrayList.push('C')
arrayList.push('E')
arrayList.insert('D','A')
arrayList.remove('E')

let toStr = arrayList.toString()
console.log(toStr)
console.log(arrayList._find('A'))
console.log(arrayList.length)